const wx = require('weixin-js-sdk')
import API from '../api/index'
import CONFIG from '@/config/index'

const jsApiList = CONFIG.wxSdk.jsApiList

class WxSdk {
    constructor(options = {}) {
        if (!options.error) {
            options.error = (e) => {
                console.group('微信SDK初始化失败')
                console.log('微信SDK初始化失败')
                console.error(e)
                console.groupEnd()
            }
        }
        if (!options.success) {
            options.success = (e) => {
                console.group('微信SDK初始化成功')
                console.log('微信SDK初始化成功')
                console.error(e)
                console.groupEnd()
            }
        }

        // .replace('https:\/\/', '')
        const hrefArr = window.location.href.split('#')
        // const url = hrefArr[0] + (hrefArr[1].split('?')[1] ? '?' + hrefArr[1].split('?')[1] : '')
        const url = hrefArr[0]
        API.wx.sdk(url).then(res => {
            res = res.data
            console.log(res)
            wx.config({
                debug: CONFIG.wxSdk.debug,
                appId: res.appid,
                timestamp: res.timestamp,
                nonceStr: res.noncestr,
                signature: res.signature,
                jsApiList
            })
            wx.ready(() => {
                console.log('微信sdk初始化成功')
                this.wx = wx
                this.wxMini = wx.miniProgram
                options.success(wx)
            })
            wx.error((e) => {
                console.error('微信sdk初始化失败', e)
                options.error(e)
            })
        }).catch(e => {
            console.error('获取wxsdk参数失败', e)
            options.error(e)
        })
    }

    $wx() {
        if (!this.wx) {
            console.warn('wxSDK初始化尚未完成')
            return
        }
        return this.wx
    }

    $wxMini() {
        if (!this.wxMini) {
            console.warn('wxSDK初始化尚未完成')
            return
        }
        return this.wxMini
    }
}

export default WxSdk
